package edu.cmu.atlub.api;

import java.io.IOException;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpConnectionManager {

    private HttpConnectionManager() {
	// intentially left blank
    }
    
    public static HttpEntity getHttpEntity(String apiUrl, HashMap<String, String> params)
	    throws ClientProtocolException, IOException {
	DefaultHttpClient httpclient = new DefaultHttpClient();

	// add the credentials for authentication
	AuthenticationManager.updateHttpClientCredentials(httpclient);

	// wrapping the parameters
	String newUrl = apiUrl;
	if (params != null) {
	    newUrl += "?";
	    for (String key : params.keySet()) {
		newUrl += key + "=" + params.get(key) + "&";
	    }
	}
	HttpRequestBase httpReq = new HttpGet(newUrl);

	HttpResponse response = httpclient.execute(httpReq);
	HttpEntity entity = response.getEntity();

	System.out.println("----------------------------------------");
	System.out.println(response.getStatusLine());
	if (entity != null) {
	    return entity;
	} else {
	    throw new ClientProtocolException();
	}
    }
}
